package socket

import (
	"pro-downloader/app/ichan"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

//升级get请求为webSocket协议
var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}


func DownloadInfo(c *gin.Context) {
	//升级get请求为webSocket协议
	websocket, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		defer websocket.Close()
		return
	}

	go sendMsg(websocket)
	go receiveMsg(websocket)
}

func receiveMsg(websocket *websocket.Conn) {
	for {
		// 读取 websocket 中的数据
		msgType, msg, err := websocket.ReadMessage()
		if err != nil {
			// 客户端关闭连接时也会进入
			fmt.Println(err)
			log.Println("客户端端口关闭")
			break
		}
		// 打印收到的数据
		fmt.Printf("msgType:%v \n",msgType)
		fmt.Println(string(msg))
	}
}

func sendMsg(ws *websocket.Conn)  {
	for {
		downInfo := <-ichan.GetDownloadInfoChan()
		//fmt.Println("接收Chan消息:",downInfo)

		jsonStr,_ := json.Marshal(gin.H{"emit":"loading","msg":downInfo})
		err := ws.WriteMessage(1, jsonStr)
		if err != nil {
			log.Println("sendMsg 发送报错")
			break
		}
		//time.Sleep(1*time.Second)
	}
}

